package cz.movie.subRenamer.util;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import cz.movie.subRenamer.model.LanguageSupport;
import cz.movie.subRenamer.model.SearchingRule;

/**
 * @author David
 * 
 */
public class LoadConfigUtil {

	private Element patterns;
	private Element languages;
	private boolean renameMovieFiles;
	private boolean deleteEmptyDirs;
	private boolean extract;
	private String outputString;
	private String defaultSubtitleLanguage;

	public LoadConfigUtil(String path) throws ParserConfigurationException, SAXException, IOException {
		Document doc = loadDocument(path);
		Element root = doc.getDocumentElement();
		NodeList rootChildren = root.getChildNodes();
		for (int i = 0; i < rootChildren.getLength(); i++) {
			Element element;
			try {
				Node item = rootChildren.item(i);
				element = (Element) item;
			} catch (ClassCastException e) {
				continue;
			}

			if ("patterns".equalsIgnoreCase(element.getNodeName())) {
				this.patterns = element;
			} else if ("renameMovieFiles".equalsIgnoreCase(element.getNodeName())) {
				renameMovieFiles = Boolean.valueOf(element.getAttribute("value"));
			} else if ("outputString".equalsIgnoreCase(element.getNodeName())) {
				outputString = element.getAttribute("value");
			} else if ("defaultSubtitleLanguage".equalsIgnoreCase(element.getNodeName())) {
				defaultSubtitleLanguage = element.getAttribute("value");
			} else if ("extract".equalsIgnoreCase(element.getNodeName())) {
				extract = Boolean.valueOf(element.getAttribute("value"));
			} else if ("deleteEmptyDirs".equalsIgnoreCase(element.getNodeName())) {
				deleteEmptyDirs = Boolean.valueOf(element.getAttribute("value"));
			} else if ("languages".equalsIgnoreCase(element.getNodeName())) {
				this.languages = element;
			}
		}
	}

	private static Document loadDocument(String path) throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		Document doc = dBuilder.parse(LoadConfigUtil.class.getClassLoader().getResourceAsStream(path));
		doc.getDocumentElement().normalize();
		return doc;
	}

	public List<SearchingRule> loadPatterns() {
		LinkedList<SearchingRule> rules = new LinkedList<SearchingRule>();
		NodeList listPattern = patterns.getChildNodes();
		for (int i = 0; i < listPattern.getLength(); i++) {
			Element pattern;
			try {
				pattern = (Element) listPattern.item(i);
			} catch (ClassCastException e) {
				continue;
			}
			SearchingRule rule = new SearchingRule();
			rule.createPattern(pattern.getTextContent());
			if ("true".equalsIgnoreCase(pattern.getAttribute("reverseOrder"))) {
				rule.setReverseOrder(true);
			}
			if ("true".equalsIgnoreCase(pattern.getAttribute("fixed"))) {
				rule.setPositionEpisodeStart(Integer.parseInt(pattern.getAttribute("episodeStart")));
				rule.setPositionSeasonStart(Integer.parseInt(pattern.getAttribute("seasonStart")));
				rule.setPositionEpisodeEnd(Integer.parseInt(pattern.getAttribute("episodeEnd")));
				rule.setPositionSeasonEnd(Integer.parseInt(pattern.getAttribute("seasonEnd")));
				rule.setFixed(true);
			} else {
				rule.setFixed(false);
			}
			rules.add(rule);
		}
		return rules;
	}

	public List<LanguageSupport> loadLanguages() {
		LinkedList<LanguageSupport> LisOflanguages = new LinkedList<LanguageSupport>();
		NodeList listLangNodes = languages.getChildNodes();
		for (int i = 0; i < listLangNodes.getLength(); i++) {
			Element languageNode;
			try {
				languageNode = (Element) listLangNodes.item(i);
			} catch (ClassCastException e) {
				continue;
			}
			LanguageSupport language = new LanguageSupport();
			language.setProperName(languageNode.getAttribute("value"));
			NodeList listAlernativeNodes = languageNode.getChildNodes();
			for (int j = 0; j < listAlernativeNodes.getLength(); j++) {
				Element alt;
				try {
					alt = (Element) listAlernativeNodes.item(j);
				} catch (ClassCastException e) {
					continue;
				}
				language.getOtherNames().add(alt.getAttribute("value"));
			}

			LisOflanguages.add(language);
		}
		return LisOflanguages;
	}

	public boolean isRenameMovieFiles() {
		return renameMovieFiles;
	}

	public String getOutputString() {
		return outputString;
	}

	public String getDefaultSubtitleLanguage() {
		return defaultSubtitleLanguage;
	}

	public boolean isDeleteEmptyDirs() {
		return deleteEmptyDirs;
	}

	public boolean isExtract() {
		return extract;
	}
}
